package cc.eddic.practice.concurrency.impl;

import cc.eddic.practice.concurrency.LogItem;
import cc.eddic.practice.concurrency.LogParser;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.*;

@Component
@Qualifier("LogItemParserWithFutureCxyImpl")
public class LogItemParserWithFutureCxyImpl implements LogParser {
    @Override
    public Map<String, List<LogItem>> parse(String folderName) {
        Map<String, List<LogItem>> resultMap = new ConcurrentHashMap<>();
        ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

        try {
            List<Future<?>> futures = new ArrayList<>();
            Files.walk(Paths.get(folderName))
                    .filter(Files::isRegularFile)
                    .filter(path -> path.toString().endsWith(".log"))
                    .forEach(logFile -> {
                        Future<?> future = executorService.submit(() -> {
                            try {
                                List<LogItem> logItems = parseLogFile(logFile.toString());
                                resultMap.put(logFile.toString(), logItems);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        });
                        futures.add(future);
                    });

            // 等待所有任务完成
            for (Future<?> future : futures) {
                try {
                    future.get();
                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            executorService.shutdown();
        }

        return resultMap;
    }

    private List<LogItem> parseLogFile(String filePath) throws IOException {
        List<LogItem> logItems = new ArrayList<>();
        List<String> lines = Files.readAllLines(Paths.get(filePath));

        LogItemParserCxyImpl logItemParser = new LogItemParserCxyImpl();

        for (String line : lines) {
            Optional<LogItem> parsedLogItem = logItemParser.parse(line);
            parsedLogItem.ifPresent(logItems::add);
        }

        return logItems;
    }
}
